const webpack = require("webpack");
// 自动打开浏览器
const OpenBrowserPlugin = require("open-browser-webpack4-plugin");
// 删除dist目录
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
// webpack v4 压缩图片
const ImageMinimizerPlugin = require("image-minimizer-webpack-plugin");
// webpack v4 压缩 CSS
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");

const webpackConfig = {
  plugins: [
    new webpack.HotModuleReplacementPlugin(), // 热更新
    new OpenBrowserPlugin({
      url: `http://localhost:${PORT}/#/`,
    }),
    // 删除dist目录
    new CleanWebpackPlugin({
      // 保留 Webpack 打包生成的资源文件（如输出的 JavaScript 文件、CSS 文件等）
      protectWebpackAssets: true,
    }),
  ],
  module: {
    rules: [
      // dev
      {
        test: /\.(png|jpg|jpeg|gif|woff|woff2|ttf)$/,
        use: {
          loader: "file-loader",
          options: {
            name: "[path][name].[contenthash:8].[ext]",
          },
        },
      },
      // prod
      {
        test: /\.(png|jpg|jpeg|gif|woff|woff2|ttf)$/,
        use: {
          loader: "url-loader",
          options: {
            limit: 5 * 1024, // < 5kb base64 ,否则产出 url 格式
            outputPath: "/media/",
            name: "[name].[contenthash:8].[ext]",
            // 设置图片的 cdn 地址（也可以统一在外面的 output 中设置，将作用于所有静态资源）
            // publicPath: 'http://cdn.abc.com'
          },
        },
      },
    ],
  },
  devServer: {
    contentBase: path.join(__dirname, "../src"),
    // webpack-cli v4
    before(app) {
      const projectDir = path.resolve();
      const mockDir = "./mock";
      app.use(mockMiddleware({ projectDir, mockDir }));
    },
  },
  // webpack v4 propd
  optimization: {
    minimizer: [
      new ImageMinimizerPlugin({
        minimizer: {
          implementation: ImageMinimizerPlugin.imageminGenerate,
          options: {
            plugins: [
              /**
               * 需要安装
               * yarn add imagemin-gifsicle imagemin-jpegtran imagemin-optipng imagemin-svgo -D
               */
              ["gifsicle", { interlaced: true }],
              ["jpegtran", { progressive: true }],
              ["optipng", { optimizationLevel: 5 }],
              [
                "svgo",
                {
                  plugins: [
                    "preset-default",
                    "prefixIds",
                    {
                      name: "sortAttrs",
                      params: {
                        xmlnsOrder: "alphabetical",
                      },
                    },
                  ],
                },
              ],
            ],
          },
        },
      }),
    ],
  },
};
module.exports = {
  webpackConfig,
};
